package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.constant.PrintConstant;
import cn.com.ejiakanghu.core.config.RedisKey;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.util.TemplateUtil;
import cn.ejiakanghu.logistics.service.TakeOrderService;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.feie.FeiEService;
import org.linlinjava.litemall.core.feie.PrinterInfo;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallShopMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.anno.OrderContentDto;
import org.linlinjava.litemall.db.vo.anno.OrderContentGoodsDto;
import org.linlinjava.litemall.db.vo.wechat.SeparateWechatData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class NoticeService {
    private Logger logger = LoggerFactory.getLogger(NoticeService.class);

    @Value("${litemall.order.url}")
    private String orderUrl;

    @Autowired
    private RedisService redisService;
    @Autowired
    private FeiEService feiEService;
    @Autowired
    private AgedmallAnnouncerLogService agedmallAnnouncerLogService;
    @Resource
    private AgedmallShopMapper agedmallShopMapper;
    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;
    @Resource
    private AgedmallAnnouncerBaseInfoMapper agedmallAnnouncerBaseInfoMapper;
    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;
    @Resource
    private AgedmallAnnouncerPrintRecordMapper agedmallAnnouncerPrintRecordMapper;
    @Resource
    private AgedmallLgMissionMapper agedmallLgMissionMapper;
    @Resource
    private TakeOrderService takeOrderService;
    @Resource
    private AgedmallLgReceiveOrderMapper agedmallLgReceiveOrderMapper;
    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void addOrderMsg(String id) {
        redisService.lpush(RedisKey.ORDER_MSG, id);
    }

//    public void sendOrderMsg() {
//        String id = redisService.brpop(RedisKey.ORDER_MSG, 10, TimeUnit.SECONDS);
//        if (StringUtils.isEmpty(id)) {
//            logger.info("当前没有订单消息");
//            return;
//        }
//
//        try {
//            send(Integer.parseInt(id),null);
//        } catch (Exception e) {
//            e.printStackTrace();
//
//            logger.info("订单消息处理失败，重新加入队列");
//            redisService.lpush(RedisKey.ORDER_MSG, id);
//        }
//    }

    public void send(Integer id,String rfid,String mac) throws Exception{
        logger.info("播报器发送开始:ID:{}，RFID：{}",id,rfid);
//        AgedmallOrderMsg agedmallOrderMsg=new AgedmallOrderMsg();
        AgedmallLgMission mission=agedmallLgMissionMapper.selectByPrimaryKey(id);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());
        if (ObjectUtil.isNull(mission)) {
            logger.error("任务id不存在,id为{}",id);
            return;
        }
        if (!canPrint(mission.getType())) {
            logger.error("任务不是配货状态，id为{}",id);
            return;
        }
//        takeOrderService.takeOrderStatChangeAnno(mission.getId(),rfid);


            AgedmallAnnouncerBaseInfoExample baseInfoExample=new AgedmallAnnouncerBaseInfoExample();
        if(StringUtils.isBlank(mac)){
            baseInfoExample.or().andDeletedEqualTo(false).andStoreIdEqualTo(agedmallLgBaseInfo.getStoreId()).
                    andTypeEqualTo(agedmallLgBaseInfo.getWarehouseType());
        }
        else{
            baseInfoExample.or().andDeletedEqualTo(false).andAnnoMacEqualTo(mac);
        }
            AgedmallAnnouncerBaseInfo agedmallAnnouncerBaseInfo = agedmallAnnouncerBaseInfoMapper.selectOneByExampleWithBLOBs(baseInfoExample);

        if (null != agedmallAnnouncerBaseInfo) {
            PrinterInfo printerInfo = JSONObject.parseObject(agedmallAnnouncerBaseInfo.getAnnoConf(), PrinterInfo.class);
            if (null != printerInfo) {
                OrderContentDto orderContentDto = null;
                String content = null;

                if(rfid.equals("-1")){
                    content="******************************";
                }
                else{
                    orderContentDto = orderContentData(agedmallLgBaseInfo.getId(),rfid,mission);
                    content = TemplateUtil.printTemplate(orderContentDto);
                }

                if (StringUtils.isEmpty(content)) {
                    return;
                }

                String result = feiEService.printMsg(printerInfo.getSn(), content);
                logger.info("播报器打印返回:{}",result);
                JSONObject object = JSONObject.parseObject(result);
                if (null != object && (int)object.get("ret") == 0) {
                    // 记录日志
                    AgedmallAnnouncerLog announcerLog = new AgedmallAnnouncerLog();
                    announcerLog.setAnnoNum(agedmallAnnouncerBaseInfo.getAnnoNum());
                    announcerLog.setStoreId(agedmallAnnouncerBaseInfo.getStoreId());
                    announcerLog.setContent(content);
                    agedmallAnnouncerLogService.add(announcerLog);
                    AgedmallAnnouncerPrintRecord printRecord=new AgedmallAnnouncerPrintRecord();
                    printRecord.setAddTime(LocalDateTime.now());
                    printRecord.setIcCard(rfid);
                    printRecord.setStoreId(agedmallLgBaseInfo.getStoreId());
                    printRecord.setBaseInfoId(agedmallLgBaseInfo.getId().intValue());
                    printRecord.setContent(content);
                    agedmallAnnouncerPrintRecordMapper.insertSelective(printRecord);
                    //修改物流表相关状态
                    logger.info("订单打印、日志完成");
                    // 怕打印出条遗漏 发短信
//                    AgedmallStore agedmallBusiAdmin = agedmallStoreService.getAgedmallBusiAdminByStoreId(agedmallOrderMsg.getStoreId());
//                    if (null != agedmallBusiAdmin&&!rfid.equals("-1")) {
//                            notifyService.notifySmsTemplate(agedmallBusiAdmin.getPhone(), NotifyType.ANNOUNCER, new String[]{agedmallOrderMsg.getOrderId() + ""});
//                    }
//                    AgedmallDeliveryManInfo agedmallDeliveryManInfo = agedmallDeliveryManInfoService.queryByStoreId(rfid);
//                    if (null != agedmallDeliveryManInfo&&!rfid.equals("-1")) {
//                        notifyService.notifySmsTemplate(agedmallDeliveryManInfo.getPhone(), NotifyType.ANNOUNCER, new String[]{agedmallOrderMsg.getOrderId()+""});
//                    }
                } else {
                    logger.info("订单消息处理失败");
                    throw new Exception();
                }
            }
        }
        else{
            logger.error("当前门店打印机不存在,订单物流id为:{}",id);
        }
    }

    /**
     * 组装订单数据
     * @return
     */
    private OrderContentDto orderContentData(Long printId, String rfid,AgedmallLgMission mission) {
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(printId);
        OrderContentDto orderContentDto = LogisticsGoodsUtil.commonDataToOrderAnno(LogisticsGoodsUtil.parseObject(agedmallLgBaseInfo.getLgContent()));
        logger.info("订单数据组装完成：{}",orderContentDto);
        orderContentDto.setOrderType(changeOrderType(agedmallLgBaseInfo.getLgType()));
        AgedmallDeliveryManInfoExample deliveryManInfoExample=new AgedmallDeliveryManInfoExample();
        deliveryManInfoExample.or().andIcCardEqualTo(rfid).andDeletedEqualTo(false);
        AgedmallDeliveryManInfo manInfo = agedmallDeliveryManInfoMapper.selectOneByExample(deliveryManInfoExample);
        String picker =manInfo.getUsername();
        orderContentDto.setPicker(picker);
        orderContentDto.setOrderUrl(mission.getId().toString());
        String selfCode=stringRedisTemplate.opsForValue().get("self-"+agedmallLgBaseInfo.getId().toString()+"-code");
        orderContentDto.setSelfCode(selfCode);
        return orderContentDto;
    }

    public String changeOrderType(Integer type){
        switch (type){
            case 8:
                return PrintConstant.PRINT_ORDER_SELF_TYPE;
            case 4:
            case 5:
                return PrintConstant.PRINT_ORDER_RETURN_TYPE;
            case 1:
            case 6:
            default:
                return PrintConstant.PRINT_ORDER_DELIVERY_TYPE;
        }
    }



    public Integer sendAllOrderMsg(String rfid,String mac) throws Exception {
        // 0-否 1-是
        Integer havePrintOrder=0;
        List<Integer> baseIdList=new ArrayList<>();
        AgedmallDeliveryManInfoExample deliveryManInfoExample=new AgedmallDeliveryManInfoExample();
        deliveryManInfoExample.or().andIcCardEqualTo(rfid).andDeletedEqualTo(false);
        AgedmallDeliveryManInfo manInfo = agedmallDeliveryManInfoMapper.selectOneByExample(deliveryManInfoExample);
        if(ObjectUtil.isNull(manInfo)){
            logger.info("当前卡没有绑定员工:{}",rfid);
            return havePrintOrder;
        }

        AgedmallLgReceiveOrderExample receiveOrderExample=new AgedmallLgReceiveOrderExample();
        receiveOrderExample.or().andLgExecTypeEqualTo(1).andPhoneEqualTo(manInfo.getPhone());
        List<AgedmallLgReceiveOrder> agedmallLgReceiveOrders = agedmallLgReceiveOrderMapper.selectByExample(receiveOrderExample);
        if(agedmallLgReceiveOrders.isEmpty()){
            logger.info("当前卡没有订单可以打印:{}",rfid);
            return havePrintOrder;
        }
        agedmallLgReceiveOrders.forEach(receiveOrder->baseIdList.add(receiveOrder.getLgBaseInfoId().intValue()));

        AgedmallLgMissionExample missionExample=new AgedmallLgMissionExample();
        missionExample.or().andMissionIsOverEqualTo(1).andTypeIn(canPrintType()).andBaseInfoIdIn(baseIdList);
        List<AgedmallLgMission> agedmallLgMissions = agedmallLgMissionMapper.selectByExample(missionExample);

        for (int i = 0; i < agedmallLgMissions.size(); i++) {
            havePrintOrder=1;
            send(agedmallLgMissions.get(i).getId(),rfid,mac);
        }
        return havePrintOrder;
    }

    public List<Integer> canPrintType(){
        List<Integer> typeList=new ArrayList<>();
        typeList.add(1);
        typeList.add(4);
        typeList.add(5);
        typeList.add(6);
        typeList.add(8);
        return typeList;
    }

    public boolean canPrint(Integer type){
        List<Integer> typeList=canPrintType();
        return typeList.contains(type);
    }


    public void changeGoodsEquState(Long equId){
        AgedmallGoodsEquExample goodsEquExample=new AgedmallGoodsEquExample();
        goodsEquExample.or().andDeletedEqualTo((byte)0).andTypeEqualTo(0).andEquIdEqualTo(equId);
        AgedmallGoodsEqu goodsEqu=new AgedmallGoodsEqu();
        goodsEqu.setDistributionType(2);
        agedmallGoodsEquMapper.updateByExampleSelective(goodsEqu,goodsEquExample);
    }

}
